package com.fly.demo.web.service.impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.fly.demo.web.entity.LoginResult;
import com.fly.demo.web.service.LoginService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @desc 登录业务处理
 * @author 00fly
 * 
 *         2019年4月29日
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService
{
    /**
     * 登录
     */
    @Override
    public LoginResult login(String userName, String password)
    {
        LoginResult loginResult = new LoginResult();
        if (userName == null || userName.isEmpty())
        {
            loginResult.setLogin(false);
            loginResult.setResult("用户名不能为空");
            return loginResult;
        }
        String msg = "";
        // 获取subject实例对象
        Subject subject = SecurityUtils.getSubject();
        // 将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        // 认证
        try
        {
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("userName", userName);
            loginResult.setLogin(true);
            return loginResult;
        }
        catch (UnknownAccountException e)
        {
            log.error(e.getMessage(), e);
            msg = "UnknownAccountException -- > 账号不存在：";
        }
        catch (IncorrectCredentialsException e)
        {
            log.error(e.getMessage(), e);
            msg = "IncorrectCredentialsException -- > 密码不正确：";
        }
        catch (AuthenticationException e)
        {
            log.error(e.getMessage(), e);
            msg = "用户验证失败";
        }
        loginResult.setLogin(true);
        loginResult.setResult(msg);
        return loginResult;
    }
    
    /**
     * 退出
     */
    @Override
    public void logout()
    {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
}
